<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// 
//  common_helper.php
//  ColdXin_CI
//  
//  Created by Will_Lee on 2011-04-04.
//  Copyright 2011 lishuzu. All rights reserved.
// 
//cutstr
function cutstr($string, $length, $dot = ' ...', $charset = 'utf8') {

	if(strlen($string) <= $length) {

		return $string;

	}
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
	$strcut = '';
	if(strtolower($charset) == 'utf-8') {
		$n = $tn = $noc = 0;
		while($n < strlen($string)) {
			$t = ord($string[$n]);

			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {

				$tn = 1; $n++; $noc++;

			} elseif(194 <= $t && $t <= 223) {

				$tn = 2; $n += 2; $noc += 2;

			} elseif(224 <= $t && $t < 239) {

				$tn = 3; $n += 3; $noc += 2;

			} elseif(240 <= $t && $t <= 247) {

				$tn = 4; $n += 4; $noc += 2;

			} elseif(248 <= $t && $t <= 251) {

				$tn = 5; $n += 5; $noc += 2;

			} elseif($t == 252 || $t == 253) {

				$tn = 6; $n += 6; $noc += 2;

			} else {

				$n++;
			}
			if($noc >= $length) {
				break;
			}
		}
		if($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);

	} else {
		for($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}
//SQL ADDSLASHES

function saddslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = saddslashes($val);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

//取消HTML代码
function shtmlspecialchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = shtmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
			str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}
//产生随机字符
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
	$seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed[mt_rand(0, $max)];
	}
	return $hash;
}

//判断字符串是否存在
function strexists($haystack, $needle) {
	return !(strpos($haystack, $needle) === FALSE);
}


//获取文件名后缀
function fileext($filename) {
	return strtolower(trim(substr(strrchr($filename, '.'), 1)));
}

//去掉slassh
function sstripslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = sstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}



//编码转换
function siconv($str, $out_charset, $in_charset='') {
	global $_SC;

	$in_charset = empty($in_charset)?strtoupper($_SC['charset']):strtoupper($in_charset);
	$out_charset = strtoupper($out_charset);
	if($in_charset != $out_charset) {
		if (function_exists('iconv') && (@$outstr = iconv("$in_charset//IGNORE", "$out_charset//IGNORE", $str))) {
			return $outstr;
		} elseif (function_exists('mb_convert_encoding') && (@$outstr = mb_convert_encoding($str, $out_charset, $in_charset))) {
			return $outstr;
		}
	}
	return $str;//转换失败
}
//ob
function obclean() {
	@ob_end_clean();
	if (config_item('compress_output') && function_exists('ob_gzhandler')) {
		ob_start('ob_gzhandler');
	} else {
		ob_start();
	}
}
//对话框
function showmessage($msgkey, $url_forward='', $second=1, $inajax=0, $values=array()) {
	$CI =& get_instance();
	obclean();
	$message = $msgkey;
	if($inajax || $CI->input->post('inajax')) {
		if($url_forward) {
			if(!strexists($url_forward, base_url()) && !strexists($url_forward, 'http://')){
				$url_forward = base_url().$url_forward;
			}
			$message = array(
				'msg' => $msgkey,
				'url_forward' => $url_forward,
				);
			if ($value) {
				$message = array_merge($message, $value);
			}
		}
		echo json_encode($message);
		ob_out();
	}else{
		if($url_forward) {
			if(!strexists($url_forward, base_url()) && !strexists($url_forward, 'http://')){
				$url_forward = base_url().$url_forward;
			}
			$message = "<a href=\"{$url_forward}\">$message</a><script>setTimeout(\"window.location.href ='{$url_forward}';\", ".($second*1000).");</script>";
		}
		$data['message'] = $message;
		$data['url_forward'] = $url_forward;
		$html = $CI->load->template('showmessage', $data, true);
		echo $html;
	}
	exit();	

}
/*debug by WillLee*/
//获取文件内容
function sreadfile($filename) {
	$content = '';
	if(function_exists('file_get_contents')) {
		@$content = file_get_contents($filename);
	} else {
		if(@$fp = fopen($filename, 'r')) {
			@$content = fread($fp, filesize($filename));
			@fclose($fp);
		}
	}
	return $content;
}

//写入文件
function swritefile($filename, $writetext, $openmod='w') {
	if(@$fp = fopen($filename, $openmod)) {
		flock($fp, 2);
		fwrite($fp, $writetext);
		fclose($fp);
		return true;
	} else {
		log_message('error', "File: $filename write error.");
		return false;
	}
}

//子模板更新检查
function subtplcheck($subfiles, $mktime, $tpl) {
	$CI =& get_instance();
	$tplrefresh = $CI->config->item('tplrefresh');
	if($tplrefresh && ($tplrefresh == 1 || mt_rand(1, $tplrefresh) == 1)) {
		$subfiles = explode('|', $subfiles);
		foreach ($subfiles as $subfile) {
			$tplfile = APPPATH.'./views/'.$subfile.'.htm';
			//如果找不到就到default里边找
			if(!file_exists($tplfile)) {
				show_error('Unable to load the requested file: '.$tplfile);
				$tplfile = str_replace('/'.$CI->config->item('template').'/', '/default/', $tplfile);
			}
			@$submktime = filemtime($tplfile);
			if($submktime > $mktime) {
				parse_template($tpl);
				break;
			}
		}
	}
}

//调整输出
function ob_out() {
	$CI =& get_instance();
	$content = ob_get_contents();
	obclean();
		if($CI->config->item('charset')) {
			@header('Content-Type: text/html; charset='.$CI->config->item('charset'));
		}
		echo $content;
		if($CI->config->item('log_threshold') != '0') {
			echo "elapsed_time:".$CI->benchmark->elapsed_time()."s<br>";
			echo "memory_usage:".$CI->benchmark->memory_usage()."<br>";
		}
}

//获取目录
function sreaddir($dir, $extarr=array()) {
	$dirs = array();
	if($dh = opendir($dir)) {
		while (($file = readdir($dh)) !== false) {
			if(!empty($extarr) && is_array($extarr)) {
				if(in_array(strtolower(fileext($file)), $extarr)) {
					$dirs[] = $file;
				}
			} else if($file != '.' && $file != '..') {
				$dirs[] = $file;
			}
		}
		closedir($dh);
	}
	return $dirs;
}

//连接字符
function simplode($ids) {
	return "'".implode("','", $ids)."'";
}

//时间格式化
function sgmdate($dateformat, $timestamp='', $format=0) {
	if(empty($timestamp)) {
		$timestamp = now();
	}
	$result = '';
	if($format) {
		$time = now() - $timestamp;
		if($time > 24*3600) {
			$result = gmdate($dateformat, $timestamp);
		} elseif ($time > 3600) {
			$result = intval($time/3600).'时'.'前';
		} elseif ($time > 60) {
			$result = intval($time/60).'分'.'前';
		} elseif ($time > 0) {
			$result = $time.'秒'.'前';
		} else {
			$result = '刚刚';
		}
	} else {
		$result = gmdate($dateformat, $timestamp);
	}
	return $result;
}
/*debug by WillLee*/
/*wirte info log*/
function writelog($file, $log) {
	global $timestamp, $_DCACHE;
	$yearmonth = gmdate('Ym', now() + 8 * 3600);
	$logdir = APPPATH.'./logs/';
	$logfile = $logdir.$yearmonth.'_'.$file.'.php';
	if(@filesize($logfile) > 2048000) {
		$dir = opendir($logdir);
		$length = strlen($file);
		$maxid = $id = 0;
		while($entry = readdir($dir)) {
			if(strexists($entry, $yearmonth.'_'.$file)) {
				$id = intval(substr($entry, $length + 8, -4));
				$id > $maxid && $maxid = $id;
			}
		}
		closedir($dir);

		$logfilebak = $logdir.$yearmonth.'_'.$file.'_'.($maxid + 1).'.php';
		@rename($logfile, $logfilebak);
	}
	if($fp = @fopen($logfile, 'a')) {
		@flock($fp, 2);
		$log = is_array($log) ? $log : array($log);
		foreach($log as $tmp) {
			fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $tmp)."\n");
		}
		fclose($fp);
	}
}

//获取在线IP
function getonlineip($format=0) {
	$CI =& get_instance();
	//得到数组
	$_SGLOBAL = ($CI->config->item('SGLOBAL'));
	if(empty($_SGLOBAL['onlineip'])) {
		if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$onlineip = getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$onlineip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$onlineip = getenv('REMOTE_ADDR');
		} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$onlineip = $_SERVER['REMOTE_ADDR'];
		}
		preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
		$_SGLOBAL['onlineip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
		//设置数组的值
		$CI->config->set_item('SGLOBAL',$_SGLOBAL);
	}
	if($format) {
		$ips = explode('.', $_SGLOBAL['onlineip']);
		for($i=0;$i<3;$i++) {
			$ips[$i] = intval($ips[$i]);
		}
		return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
	} else {
		return $_SGLOBAL['onlineip'];
	}	
}
//对话框
function showjsonmessage($msgkey,$code, $values=array()) {
	$CI =& get_instance();
	$json_arr = array();
	obclean();
	$json_arr['msg'] = $msgkey;
	$json_arr['code'] = $code;
	if ($values) {
		foreach ($values as $key => $value) {
			$json_arr[$key] = $value;
		}
	}
	echo json_encode($json_arr);
	exit();
}

//http 模拟
function dfopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
	$return = '';
	$matches = parse_url($url);
	$host = $matches['host'];
	$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
	$port = !empty($matches['port']) ? $matches['port'] : 80;

	if($post) {
		$out = "POST $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		//$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= 'Content-Length: '.strlen($post)."\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cache-Control: no-cache\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
		$out .= $post;
	} else {
		$out = "GET $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		//$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
	}
	$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
	if(!$fp) {
		return '';
	} else {
		stream_set_blocking($fp, $block);
		stream_set_timeout($fp, $timeout);
		@fwrite($fp, $out);
		$status = stream_get_meta_data($fp);
		if(!$status['timed_out']) {
			while (!feof($fp)) {
				if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
					break;
				}
			}

			$stop = false;
			while(!feof($fp) && !$stop) {
				$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
				$return .= $data;
				if($limit) {
					$limit -= strlen($data);
					$stop = $limit <= 0;
				}
			}
		}
		@fclose($fp);
		return $return;
	}
}
// 上传文件
function upload_file($config = array()){
	$CI = & get_instance();
	$default_config = $CI->config->item('upload_config', 'SGLOBAL');
	if ($config) {
		foreach ($config as $key => $value){
			if ($value) {
				$default_config[$key] = $value;
			}
		}
	}
	$path = makepath($default_config['upload_path']);
	$default_config['upload_path'] = $path;
	$CI->file->forcemkdir($path);
	// $CI->file->createaccessfile($path);
	
	$CI->load->library('upload', $default_config);
	if (!$CI->upload->do_upload($default_config['formname'])){
		$error = array('error' => $CI->upload->display_errors());
		return $error;
	}else{
		$data = array('upload_data' => $CI->upload->data());
		$patharr = pathinfo($default_config['upload_path']);
		$data['upload_data']['basename'] = $patharr['basename'];
		return $data;
	}
}
// 创建目录
function makepath($path, $format='Ym'){
	return $path.gmdate($format, now())."/";
}

function url_formate($url, $param= array()){
	$CI = & get_instance();
	$key_str = '';
	$str = $url.'|';
	if ($param) {
		foreach ($param as $key => $value) {
			$data[$key] = xss_clean($value);
			$key_str .= $value;
		}
	}
	$data['url'] = xss_clean($url);
	$data['key'] = md5($key_str.$CI->config->item('encryption_key'));
	$jumpurl = base_url().'jump/index/?param='.base64_encode(json_encode($data));
	return $jumpurl;
}
?>